package test21.homeWork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Homework03Server {
    public static void main(String[] args) throws IOException {
        //监听 9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //等待客户端连接
        System.out.println("服务端，在9999端口监听，等待下载文件");
        Socket socket = serverSocket.accept();
        //读取 客户端发送要下载的文件名
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        String downLoadFileName = "";
        while ((len = inputStream.read()) != -1){
            downLoadFileName += new String(b,0,len);
        }
        System.out.println("客户端希望下载文件名=" + downLoadFileName);

        //服务器上有两个文件, 无名.mp3 高山流水.mp3
        //如果客户下载的是 高山流水 我们就返回该文件，否则一律返回 无名.mp3
        String resFileName = "";
        if("高山流水".equals(downLoadFileName)) {
            resFileName = "src\\test21\\homeWork\\高山流水.mp3";
        } else {
            resFileName = "src\\test21\\homeWork\\无名.mp3";
        }
        //创建一个输入流，读取文件
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(resFileName));
        byte[] array = StreamUtils.streamToByteArray(bufferedInputStream);
        //得到Socket关联的输出流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(array);
        socket.shutdownOutput();
        bufferedOutputStream.flush();

        bufferedInputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出...");

    }
}
